<template lang="pug">
  v-data-table(
    v-model="selected"
    :headers="OrderItemDataTableDef.headers"
    :items="orderItemsClone"
    item-key="name"
    disable-pagination=true
    hide-default-footer=true
    show-select=true
    disable-sort=true)
    template(v-slot:item.quantity="{item}")
      span(v-show="showAvailableCount(item)") 可用 : {{ getItemAvailableCount(item) }}
      v-btn(text icon color="primary" v-show="isShowAction(item)" @click="changeQuantity(item, -1)")
        v-icon mdi-minus
      v-btn(text icon color="primary" v-show="isShowAction(item)" @click="changeQuantity(item, 1)")
        v-icon mdi-plus
      span {{ item.quantity }}


    template(v-slot:item.netPrice="{item}")
      span {{ getPrice(item) }}
</template>

<script lang="ts">
  import Vue, {VueConstructor} from 'vue'
  import {mapMutations, mapState} from 'vuex'
  import {OrderItem, OrderItemDataTableDef, OrderItemType} from '@/store/modules/types/Order'
  import {debounce} from 'lodash'



  export default (Vue as VueConstructor<Vue & {}>).extend({
    name: 'order_asset_items',
    methods: {
      ...mapMutations('order', ['removeAssets']),
      getItemAvailableCount(item: OrderItem) {
        if (item.rentalable_type == OrderItemType.AssetStock) {
          return item.rentalable.available_quantity - item.quantity
        }
        return 1
      },
      showAvailableCount(item: OrderItem) {
        return this.activeAsset == item.name
      },
      deleteSelected() {
        this.removeAssets(this.selected)
        this.selected = []
      },
      isShowAction(item: OrderItem) {
        return item.rentalable_type == OrderItemType.AssetStock
      },
      clearActiveAsset: debounce(function(){
        this.activeAsset = null
      }, 3000),
      changeQuantity(item: OrderItem, step: number) {
        this.activeAsset = item.name
        if (item.quantity === 1 && step === -1) {
          return
        }
        let availableCount = item.rentalable.available_quantity
        if (item.quantity === availableCount && step === 1) {
          return
        }
        item.quantity = item.quantity + step
        let vm = this
        this.clearActiveAsset()
      },
      getPrice(item: OrderItem) {
        return item.unitPrice * item.quantity
      }
    },
    computed: {
      ...mapState('order', ['orderItemsClone']),
    },
    data() {
      return {
        activeAsset: null,
        OrderItemDataTableDef,
        selected: []
      }
    }
  })
</script>